<!--
  通知详情组件
  @description 通知记录详情对话框，展示通知的详细信息
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="t('sop.notify.detail')" width="1000px">
    <el-row :gutter="20" v-loading="formLoading">
      <!-- 基本信息 -->
      <el-col :span="24">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>{{ t('sop.notify.basicInfo') }}</span>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item :label="t('sop.notify.id')">
              {{ formData.id }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.appId')">
              {{ formData.appId }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.merchantNo')">
              {{ formData.merchantNo }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.notifyType')">
              <dict-tag :type="DICT_TYPE.SOP_NOTIFY_TYPE" :value="formData.notifyType" />
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.notifyStatus')">
              <dict-tag :type="DICT_TYPE.SOP_NOTIFY_STATUS" :value="formData.notifyStatus" />
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.retryCount')">
              <el-tag :type="formData.retryCount > 3 ? 'danger' : 'info'">
                {{ formData.retryCount }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.createTime')">
              {{ formatDate(formData.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.lastNotifyTime')">
              {{ formatDate(formData.lastNotifyTime) }}
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.nextRetryTime')">
              {{ formatDate(formData.nextRetryTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 通知信息 -->
      <el-col :span="24">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>{{ t('sop.notify.notifyInfo') }}</span>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item :label="t('sop.notify.notifyUrl')">
              <el-link :href="formData.notifyUrl" target="_blank" type="primary">
                {{ formData.notifyUrl }}
              </el-link>
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.notifyData')">
              <el-input
                v-model="formData.notifyData"
                type="textarea"
                :rows="6"
                readonly
                class="json-textarea"
              />
              <div class="mt-2">
                <el-button size="small" @click="copyNotifyData">
                  <Icon icon="ep:copy-document" class="mr-1" />
                  {{ t('sop.common.copy') }}
                </el-button>
                <el-button size="small" @click="formatJson">
                  <Icon icon="ep:magic-stick" class="mr-1" />
                  {{ t('sop.notify.formatJson') }}
                </el-button>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 响应信息 -->
      <el-col :span="24">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>{{ t('sop.notify.responseInfo') }}</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item :label="t('sop.notify.responseCode')">
              <el-tag :type="getResponseCodeType(formData.responseCode)">
                {{ formData.responseCode }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.responseTime')">
              {{ formData.responseTime }}ms
            </el-descriptions-item>
            <el-descriptions-item :label="t('sop.notify.responseBody')" :span="2">
              <el-input
                v-model="formData.responseBody"
                type="textarea"
                :rows="4"
                readonly
                class="json-textarea"
              />
              <div class="mt-2">
                <el-button size="small" @click="copyResponseBody">
                  <Icon icon="ep:copy-document" class="mr-1" />
                  {{ t('sop.common.copy') }}
                </el-button>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 错误信息 -->
      <el-col :span="24" v-if="formData.errorMessage">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>{{ t('sop.notify.errorInfo') }}</span>
            </div>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item :label="t('sop.notify.errorMessage')">
              <el-text type="danger">{{ formData.errorMessage }}</el-text>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('sop.common.close') }}</el-button>
      <el-button
        type="warning"
        @click="handleRetry"
        v-hasPermi="['sop:notify:retry']"
        :disabled="formData.notifyStatus === 1"
      >
        <Icon icon="ep:refresh-right" class="mr-1" />
        {{ t('sop.notify.retry') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts" name="NotifyDetail">
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import * as NotifyApi from '@/api/sop/notify'
import { NotifyVO } from '@/api/sop/types'

/** 通知详情 */
defineOptions({ name: 'NotifyDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const formData = ref<NotifyVO>({})

/** 打开弹窗 */
const open = async (data: NotifyVO) => {
  dialogVisible.value = true
  resetForm()
  formLoading.value = true
  try {
    formData.value = await NotifyApi.getNotifyApi(data.id!)
  } finally {
    formLoading.value = false
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  formData.value = {}
}

/** 获取响应码类型 */
const getResponseCodeType = (code: number) => {
  if (code >= 200 && code < 300) return 'success'
  if (code >= 400 && code < 500) return 'warning'
  if (code >= 500) return 'danger'
  return 'info'
}

/** 复制通知数据 */
const copyNotifyData = async () => {
  try {
    await navigator.clipboard.writeText(formData.value.notifyData || '')
    message.success(t('sop.common.copySuccess'))
  } catch {
    message.error(t('sop.common.copyFailed'))
  }
}

/** 复制响应数据 */
const copyResponseBody = async () => {
  try {
    await navigator.clipboard.writeText(formData.value.responseBody || '')
    message.success(t('sop.common.copySuccess'))
  } catch {
    message.error(t('sop.common.copyFailed'))
  }
}

/** 格式化JSON */
const formatJson = () => {
  try {
    const parsed = JSON.parse(formData.value.notifyData || '{}')
    formData.value.notifyData = JSON.stringify(parsed, null, 2)
  } catch {
    message.error(t('sop.notify.invalidJson'))
  }
}

/** 重试通知 */
const handleRetry = async () => {
  try {
    await message.confirm(t('sop.notify.retryConfirm'))
    await NotifyApi.retryNotifyApi(formData.value.id!)
    message.success(t('sop.notify.retrySuccess'))
    dialogVisible.value = false
    emit('success')
  } catch {}
}

defineExpose({ open }) // 提供 open 方法
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.json-textarea {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.json-textarea :deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}
</style>
